/*
 * MyLittlePony.c
 *
 * Created: 19.02.2013 20:33:52
 *  Author: Jon-Haakon
 */ 
#include <avr/io.h>

#define LED_PORT PORTB
#define LED_DDR  DDRB

#define SWITCH_PORT PORTB
#define SWITCH_DDR  DDRB
#define SWITCH_PIN  PINB

#define SW0  0
#define SW1  1
#define SW2  2

#define LED0 0
#define LED1 3
#define LED2 1
#define LED3 2

#define ON  1
#define OFF 0

void led_on (uint8_t led);       // Turn on the led
void led_off(uint8_t led);       // Turn off the led

char read_switch (uint8_t sw);   // return value of sw

int main(void){
	LED_DDR |= (1 << LED1)|(1 << LED3);	//	Set led port 2 and 3 as output
	SWITCH_DDR &= ~((1 << SW0)|(1 << SW1));	//	Set switch port 0 and 1 as input (by def 0 so not necessary)
	SWITCH_PORT |= (1 << SW0)|(1 << SW1);	//	Enable pull-up on switch port 0 and 1
	
	char sw0, sw1, sw0_last, sw1_last, led1_on, led3_on = OFF;
	
    while(1){
        sw0 = read_switch(SW0);
		sw1 = read_switch(SW1);
		
		//	Toggles LED3 on/off when pressed
		if (sw0_last == OFF && sw0 == ON){
			if (led3_on){
				led_off(LED3);
				led3_on = OFF;
			}else{
				led_on(LED3);
				led3_on = ON;
			}
		}
		
		//	Toggles LED1 on/off when pressed
		if (sw1_last == OFF && sw1 == ON){
			if (led1_on){
				led_off(LED1);
				led1_on = OFF;
			}else{
				led_on(LED1);
				led1_on = ON;
			}
		}
		
		sw0_last = sw0;
		sw1_last = sw1;
    }
}

void led_on (uint8_t led){
	// write the LED_PORT register to set the led
	// How can you do this without affecting the other leds?
	// remember that the led is on when the output is 0/GND!
	LED_PORT &= ~(1 << led);
}
void led_off(uint8_t led){
	// write the LED_PORT register to clear the led
	LED_PORT |= (1 << led);
}

char read_switch (uint8_t sw){
	// read the state of the switch and return it.
	// how can you read the state of only one switch without being disturbed by the others?
	// remember that when the switch is pressed, the input is 0

	if (!(SWITCH_PIN & (1 << sw))){
		return ON;
	}else{
		return OFF;
	}
}